package com.example.multitenant.multitenant.config

import com.example.multitenant.base.Log
import org.hibernate.cfg.AvailableSettings
import org.hibernate.context.spi.CurrentTenantIdentifierResolver
import org.springframework.boot.autoconfigure.orm.jpa.HibernatePropertiesCustomizer
import org.springframework.stereotype.Component

/**
 * @author xiang
 * @Date 2022/8/29 10:10
 **/

@Component
class TenantIdentifierResolver : CurrentTenantIdentifierResolver, HibernatePropertiesCustomizer {

    companion object{
        private const val TAG = "TenantIdentifierResolver"
    }

    override fun resolveCurrentTenantIdentifier(): String {
        val id = TenantContext.getTenantId()
        Log.i(TAG, "resolveCurrentTenantIdentifier: $id")
        return id
    }

    override fun validateExistingCurrentSessions(): Boolean {
        return true
    }

    override fun customize(hibernateProperties: MutableMap<String, Any>?) {
        hibernateProperties?.put(AvailableSettings.MULTI_TENANT_IDENTIFIER_RESOLVER, this)
    }
}